//
// Created by 崔世强 on 2018/4/11.
// Copyright (c) 2018 Facebook. All rights reserved.
//

import Foundation

class SessionService {
    
    func removeSession(sessionServerId: Int,chatType:  ChatType, complete: @escaping (_ success:Bool, _ msg:String?) -> Void) {
        do {
//            try SessionDao.delete(sessionServerId)
            try SessionDao.realDelete(sessionServerId,chatType: chatType)
            try MessageDao.delete(sessionId: sessionServerId,chatType: chatType)
            complete(true, nil)
        } catch {
            print(error)
            complete(false, error.localizedDescription)
        }
    }
    
    func getRecentSessions() -> [ChatSession] {
        var chatSessions = [ChatSession]()
        if !AppStatusManager.instance.userLoginStatus.0 {
            return chatSessions
        }
        do {
            let sessions = try SessionDao.getRecentSessions()
            for session in sessions {
                let chatSession = ChatSession()
                chatSession.session = session
                switch session.chatType {
                case .p2p:
                    let contact = try ContactDao.getContact(session.sessionServerId)
                    chatSession.sessionName = contact?.remarkName ?? contact?.name
                    chatSession.avatar = contact?.avatar
                case .group:
                    if let group = try GroupDao.getGroup(session.sessionServerId){
                        let members = try GroupDao.getMembers(session.sessionServerId, limit: 9)
                        var groupName = ""
                        var avatars = [String]()
                        if members.count > 0 {
                            for member in members {
                                let memContact = try ContactDao.getContact(member.userId)
                                groupName  = groupName + "\(memContact?.remarkName ?? member.nickName ?? memContact?.name ?? "陌生人")、"
                                avatars.append(memContact?.avatar ?? "")
                            }
                            groupName = groupName.substring(s:0,-1)
                        }
                        
                        chatSession.sessionName = isEmpty(group.name) ? groupName : group.name!
                    } else {
                        chatSession.sessionName = "群聊"
                    }
                default:
                    return chatSessions
                }
                chatSessions.append(chatSession)
            }
        } catch {
            print(error)
        }
        return chatSessions
    }
    
    func isEmpty(_ str:String?) -> Bool {
        return !(str != nil && !str!.isEmpty)
    }
    
    //获取所有的 (单聊和群聊) 的会话列表
    func getAllRecentSessions() -> [ChatSession] {
        var chatSessions = [ChatSession]()
        if !AppStatusManager.instance.userLoginStatus.0 {
            return chatSessions
        }
        do {
            let db = SQLiteHelper.getDb()
            try db.run(transaction: { _ in
                let sessions = try SessionDao.getAllRecentSessions()
                for session in sessions {
                    let chatSession = ChatSession()
                    chatSession.session = session
                    //获取最新消息
                    let lastMsg = try MessageDao.getLastMsg(sessionServerId: session.sessionServerId,chatType: session.chatType)
                    chatSession.lastMsg = lastMsg
                    //获取未读消息数
                    let unreadCount = try MessageDao.getUnreadCount(sessionServerId: session.sessionServerId, chatType: session.chatType)
                    chatSession.unreadCount = unreadCount
                    switch session.chatType {
                    case .p2p:
                        if let contact = try ContactDao.getContact(session.sessionServerId) {
                            chatSession.sessionName = contact.remarkName ?? contact.name
                            chatSession.avatar = contact.avatar
                        }else {
                            chatSession.sessionName = "\(session.sessionServerId)"
                        }
                    case .group:
                        //群聊
                        if let group = try GroupDao.getGroup(session.sessionServerId) {
                            chatSession.avatar = group.avatar
                            chatSession.noDisturbing = group.noDisturb
                            chatSession.top = group.top
                            let groupmemberList = try GroupDao.getMembers(group.groupId, limit: 9)
                            var sessionName = ""
                            for groupMember in groupmemberList {
                                if groupMember.userId == AppStatusManager.instance.userLoginStatus.1 {
                                    chatSession.avatars.append(AppStatusManager.instance.avatar ?? "timg")
                                    sessionName += (groupMember.nickName ?? AppStatusManager.instance.userLoginStatus.2 ?? "\(groupMember.userId)") + "、"
                                } else {
                                    let contact = try ContactDao.getContact(groupMember.userId)
                                    chatSession.avatars.append(contact?.avatar ?? "timg")
                                    sessionName += (contact?.remarkName ?? groupMember.nickName ?? contact?.name ?? "\(groupMember.userId)") + "、"
                                }
                            }
                            if sessionName.count > 0 {
                                sessionName = sessionName.substring(s: 0,-1)
                            }
                            if groupmemberList.isEmpty {
                                chatSession.avatars.append("")
                                sessionName = "群聊"
                            }
                            chatSession.sessionName = group.name ?? sessionName
                        } else {
                            chatSession.avatars.append("")
                            chatSession.sessionName = "群聊"
                        }
                        break
                    default:
                        continue
                    }
                    chatSessions.append(chatSession)
                }
            })
        }catch {
            print(error)
        }
        return chatSessions
    }
    
    //根据 chatType 获取最近会话列表
    func getRecentSessions(chatType:ChatType) -> [ChatSession] {
        var chatSessions = [ChatSession]()
        if !AppStatusManager.instance.userLoginStatus.0 {
            return chatSessions
        }
        
        do {
            let db = SQLiteHelper.getDb()
            try db.run(transaction: { _ in
                let sessions = try SessionDao.getRecentSessions(chatType:chatType)
                for session in sessions {
                    let chatSession = ChatSession()
                    chatSession.session = session
                    //获取最新消息
                    let lastMsg = try MessageDao.getLastMsg(sessionServerId: session.sessionServerId, chatType: session.chatType)
                    chatSession.lastMsg = lastMsg
                    //获取未读消息数
                    let unreadCount = try MessageDao.getUnreadCount(sessionServerId: session.sessionServerId,chatType: chatType)
                    chatSession.unreadCount = unreadCount
                    
                    if chatType == .p2p {
                        if let contact = try ContactDao.getContact(session.sessionServerId) {
                            chatSession.sessionName = contact.remarkName ?? contact.name
                            chatSession.avatar = contact.avatar
                            //              if contact.avatar != nil {
                            //                chatSession.avatars.append(contact.avatar!)
                            //              }
                        }else {
                            chatSession.sessionName = "单聊"
                        }
                    } else if (chatType == .group) {
                        //群聊
                        if let group = try GroupDao.getGroup(session.sessionServerId) {
                            chatSession.avatar = group.avatar
                            chatSession.noDisturbing = group.noDisturb
                            chatSession.top = group.top
                            let groupmemberList = try GroupDao.getMembers(group.groupId, limit: 9)
                            var sessionName = ""
                            for groupMember in groupmemberList {
                                let contact = try ContactDao.getContact(groupMember.userId)
                                chatSession.avatars.append(contact?.avatar ?? "timg")
                                sessionName += (contact?.remarkName ?? groupMember.nickName ?? contact?.name ?? "陌生人") + "、"
                            }
                            if sessionName.count > 0 {
                                sessionName = sessionName.substring(s: 0,-1)
                            }
                            if groupmemberList.isEmpty {
                                chatSession.avatars.append("")
                                sessionName = "群聊"
                            }
                            chatSession.sessionName = group.name ?? sessionName
                        }
                    }else if (chatType == .service_platform){
                        //服务平台
                        if let group = try GroupDao.getGroup(session.sessionServerId) {
                            chatSession.avatar = group.avatar
                            chatSession.noDisturbing = group.noDisturb
                            chatSession.top = group.top
                            let groupmemberList = try GroupDao.getMembers(group.groupId, limit: 9)
                            var sessionName = ""
                            for groupMember in groupmemberList {
                                let contact = try ContactDao.getContact(groupMember.userId)
                                chatSession.avatars.append(contact?.avatar ?? "timg")
                                sessionName += (contact?.remarkName ?? groupMember.nickName ?? contact?.name ?? "陌生人") + "、"
                            }
                            if sessionName.count > 0 {
                                sessionName = sessionName.substring(s: 0,-1)
                            }
                            if groupmemberList.isEmpty {
                                chatSession.avatars.append("")
                                sessionName = "群聊"
                            }
                            chatSession.sessionName = group.name ?? sessionName
                        }
                    }
                    chatSessions.append(chatSession)
                }
            })
        }catch {
            print(error)
        }
        return chatSessions
    }
}


